package com.alasbusy.alasbusyapp.utils;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.content.ContentResolver;
import android.content.Context;
import android.net.ParseException;
import android.text.TextUtils;
import android.widget.DatePicker;
import android.widget.TextView;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Locale;

public class TimeUtil {

    /**
     * yyyy-MM-dd HH:mm:ss
     */
    @SuppressLint("SimpleDateFormat")
    public static String getNowYMDHMSTime() {
        SimpleDateFormat mDateFormat = new SimpleDateFormat(
            "yyyy-MM-dd HH:mm:ss");
        return mDateFormat.format(new Date());
    }

    /**
     * MM-dd HH:mm:ss
     */
    @SuppressLint("SimpleDateFormat")
    public static String getNowMDHMSTime() {
        SimpleDateFormat mDateFormat = new SimpleDateFormat(
            "MM-dd HH:mm:ss");
        return mDateFormat.format(new Date());
    }

    /**
     * MM-dd
     */
    @SuppressLint("SimpleDateFormat")
    public static String getNowYMD() {

        SimpleDateFormat mDateFormat = new SimpleDateFormat(
            "yyyy-MM-dd");
        return mDateFormat.format(new Date());
    }

    /**
     * yyyy-MM-dd
     */
    @SuppressLint("SimpleDateFormat")
    public static String getYMD(Date date) {

        SimpleDateFormat mDateFormat = new SimpleDateFormat(
            "yyyy-MM-dd");
        return mDateFormat.format(date);
    }

    @SuppressLint("SimpleDateFormat")
    public static String getMD(Date date) {

        SimpleDateFormat mDateFormat = new SimpleDateFormat(
            "MM-dd");
        return mDateFormat.format(date);
    }


    /**
     * 根据年月日 日期取得星期几
     *
     * @param stringDate 默认年月日格式为yyyy-MM-dd
     * @return 返回当前时间是星期几
     */
    public static String getWeek(String stringDate) {
        Date date = stringToDate(stringDate, "yyyy-MM-dd");
        SimpleDateFormat sdf = new SimpleDateFormat("EEEE");
        String week = sdf.format(date);
        return week;
    }

    // strTime要转换的string类型的时间，formatType要转换的格式yyyy-MM-dd HH:mm:ss//yyyy年MM月dd日
    // HH时mm分ss秒，
    // strTime的时间格式必须要与formatType的时间格式相同
    public static Date stringToDate(String strTime, String formatType)
            throws ParseException {
        SimpleDateFormat formatter = new SimpleDateFormat(formatType);
        Date date = null;
        try {
            date = formatter.parse(strTime);
        } catch (java.text.ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return date;
    }

    // formatType格式为yyyy-MM-dd HH:mm:ss//yyyy年MM月dd日 HH时mm分ss秒
    // data Date类型的时间
    public static String dateToString(Date data, String formatType) {
        return new SimpleDateFormat(formatType).format(data);
    }

    // formatType格式为yyyy-MM-dd HH:mm:ss//yyyy年MM月dd日 HH时mm分ss秒
    // data Date类型的时间
    public static String longToString(long currentTime, String formatType)
            throws ParseException {
        Date date = longToDate(currentTime, formatType); // long类型转成Date类型
        String strTime = dateToString(date, formatType); // date类型转成String
        return strTime;
    }


    // currentTime要转换的long类型的时间
    // formatType要转换的时间格式yyyy-MM-dd HH:mm:ss//yyyy年MM月dd日 HH时mm分ss秒
    public static Date longToDate(long currentTime, String formatType)
            throws ParseException {
        Date dateOld = new Date(currentTime); // 根据long类型的毫秒数生命一个date类型的时间
        String sDateTime = dateToString(dateOld, formatType); // 把date类型的时间转换为string
        Date date = stringToDate(sDateTime, formatType); // 把String类型转换为Date类型
        return date;
    }

    // strTime要转换的String类型的时间
    // formatType时间格式
    // strTime的时间格式和formatType的时间格式必须相同
    public static long stringToLong(String strTime, String formatType)
            throws ParseException {
        Date date = stringToDate(strTime, formatType); // String类型转成date类型
        if (date == null) {
            return 0;
        } else {
            long currentTime = dateToLong(date); // date类型转成long类型
            return currentTime;
        }
    }

        // date要转换的date类型的时间
    public static long dateToLong(Date date) {
        return date.getTime();
    }

    /**
     * 秒转HH:mm:ss
     * @param time
     * @return
     */
    public static String secToTime(int time) {
        String timeStr = null;
        int hour = 0;
        int minute = 0;
        int second = 0;
        if (time <= 0)
            return "00:00";
        else {
            minute = time / 60;
            if (minute < 60) {
                second = time % 60;
                timeStr = unitFormat(minute) + ":" + unitFormat(second);
            } else {
                hour = minute / 60;
                if (hour > 99)
                    return "99:59:59";
                minute = minute % 60;
                second = time - hour * 3600 - minute * 60;
                timeStr = unitFormat(hour) + ":" + unitFormat(minute) + ":" + unitFormat(second);
            }
        }
        return timeStr;
    }

    public static String unitFormat(int i) {
        String retStr = null;
        if (i >= 0 && i < 10)
            retStr = "0" + Integer.toString(i);
        else
            retStr = "" + i;
        return retStr;
    }


    public static void showDatePickerDialog(Activity activity, int themeResId, final TextView tv, Calendar calendar) {
        // 直接创建一个DatePickerDialog对话框实例，并将它显示出来
        new DatePickerDialog(activity , themeResId,new DatePickerDialog.OnDateSetListener() {
            // 绑定监听器(How the parent is notified that the date is set.)
            @Override
            public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                // 此处得到选择的时间，可以进行你想要的操作
                tv.setText(year + "-" + (monthOfYear+1)+ "-" + dayOfMonth);
            }
        }
                // 设置初始日期
                , calendar.get(Calendar.YEAR)
                ,calendar.get(Calendar.MONTH)
                ,calendar.get(Calendar.DAY_OF_MONTH)).show();
    }

    /**
     * 得到现在分钟
     *
     * @return
     */
    public static String getMinute() {
        Date currentTime = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateString = formatter.format(currentTime);
        String min;
        min = dateString.substring(14, 16);
        return min;
    }


    /**
     * 根据系统时间判断当前时间是白天还是夜晚
     *
     * @param context
     * @return true:白天，false：夜晚
     */
    public static boolean getSystimeDayOrNight(Context context) {
        boolean action = false;
        //获得内容提供者
        ContentResolver mResolver = context.getContentResolver();
        //获得系统时间制
        String timeFormat = android.provider.Settings.System.getString(mResolver, android.provider.Settings.System.TIME_12_24);
        if (TextUtils.isEmpty(timeFormat)) {
            return false;
        }
        //判断时间制
        else if (timeFormat.equals("24")) {   //24小时制
            Calendar calendar = GregorianCalendar.getInstance();
            calendar.setTime(new Date());
            int hourOfDay = calendar.get(Calendar.HOUR_OF_DAY);
            int minute = Integer.parseInt(TimeUtil.getMinute());
            int second = calendar.get(Calendar.SECOND);
            //Log.d("dayType","24小时制，get hourOfDay == "+hourOfDay);
            if (hourOfDay > 6 && hourOfDay < 19) {//规定早上6点到下午7点为白天
                action = true;
            } else {//其他时间为晚上
                action = false;
            }
        } else { //12小时制
            //获得日历
            Calendar mCalendar = Calendar.getInstance();
            int hourOfDay = mCalendar.get(Calendar.HOUR_OF_DAY);
            int minute = Integer.parseInt(TimeUtil.getMinute());
            int second = mCalendar.get(Calendar.SECOND);
            if (mCalendar.get(Calendar.AM_PM) == 0) { //白天

                action = true;
            } else { //晚上
                action = false;
            }
            //Log.d("dayType","12小时制");
        }

        return action;
    }

    /**
     * 根据系统时间判断当前时间是AM 还是 PM
     *
     * @param context
     * @return blnAMorPM
     */
    public static boolean getSystimeAMorPM(Context context) {
        boolean blnAMorPM = false;
        //获得内容提供者
        ContentResolver mResolver = context.getContentResolver();
        //获得系统时间制
        String timeFormat = android.provider.Settings.System.getString(mResolver, android.provider.Settings.System.TIME_12_24);
        if (TextUtils.isEmpty(timeFormat)) {
            return false;
        }
        //判断时间制
        else if (timeFormat.equals("24")) {
            //24小时制
            Calendar calendar = GregorianCalendar.getInstance();
            calendar.setTime(new Date());
            int hourOfDay = calendar.get(Calendar.HOUR_OF_DAY);
            int minute = Integer.parseInt(TimeUtil.getMinute());
            if (hourOfDay > 6 && hourOfDay < 19) {//规定早上6点到下午7点为白天
                if (hourOfDay <= 12) {
                    blnAMorPM = true;
                } else {
                    blnAMorPM = false;
                }
            } else {//其他时间为晚上
                blnAMorPM = false;
            }
            //Log.d("dayType", "24小时制");
        } else {
            //12小时制
            //获得日历
            Calendar mCalendar = Calendar.getInstance();
            int hourOfDay = mCalendar.get(Calendar.HOUR_OF_DAY);
            int minute = Integer.parseInt(TimeUtil.getMinute());
            if (mCalendar.get(Calendar.AM_PM) == 0) {    //白天
                if (hourOfDay <= 12) {
                    blnAMorPM = true;
                } else {
                    blnAMorPM = false;
                }
            } else {   //晚上
                //晚上8点整
                if (hourOfDay == 8 && minute == 00) {
                    blnAMorPM = false;
                }
                //凌晨12点
                if (hourOfDay == 00 && minute == 00) {
                    blnAMorPM = true;
                }
            }
            //Log.d("dayType", "12小时制");
        }

        return blnAMorPM;
    }

    /******************Android小工具之智能格式化时间**********************************
     * http://www.jianshu.com/p/c819918240b3
     * 看着别人的应用的时间显示着“刚刚”、“2分钟之前”、“下午 2:00”是不是很羡慕？但是常常因为项目时间紧凑，
     * 没空去扣这些细节的你一定很想要一个这样的小工具啦，这里就送大家一个这样的格式化时间小工具：
     */

    /**
     * @param date
     * @return
     */

    public static String formatDateTime(Date date) {
        String text;
        long dateTime = date.getTime();
        if (isSameDay(dateTime)) {
            Calendar calendar = GregorianCalendar.getInstance();
            if (inOneMinute(dateTime, calendar.getTimeInMillis())) {
                return "刚刚";
            } else if (inOneHour(dateTime, calendar.getTimeInMillis())) {
                return String.format("%d分钟之前", Math.abs(dateTime - calendar.getTimeInMillis()) / 60000);
            } else {
                calendar.setTime(date);
                int hourOfDay = calendar.get(Calendar.HOUR_OF_DAY);
                if (hourOfDay > 17) {
                    text = "晚上 hh:mm";
                } else if (hourOfDay >= 0 && hourOfDay <= 6) {
                    text = "凌晨 hh:mm";
                } else if (hourOfDay > 11 && hourOfDay <= 17) {
                    text = "下午 hh:mm";
                } else {
                    text = "上午 hh:mm";
                }
            }
        } else if (isYesterday(dateTime)) {
            text = "昨天 HH:mm";
        } else if (isSameYear(dateTime)) {
            text = "M月d日 HH:mm";
        } else {
            text = "yyyy-M-d HH:mm";
        }

        // 注意，如果使用android.text.format.DateFormat这个工具类，在API 17之前它只支持adEhkMmszy
        return new SimpleDateFormat(text, Locale.CHINA).format(date);
    }

    private static boolean inOneMinute(long time1, long time2) {
        return Math.abs(time1 - time2) < 60000;
    }

    private static boolean inOneHour(long time1, long time2) {
        return Math.abs(time1 - time2) < 3600000;
    }

    private static boolean isSameDay(long time) {
        long startTime = floorDay(Calendar.getInstance()).getTimeInMillis();
        long endTime = ceilDay(Calendar.getInstance()).getTimeInMillis();
        return time > startTime && time < endTime;
    }

    private static boolean isYesterday(long time) {
        Calendar startCal;
        startCal = floorDay(Calendar.getInstance());
        startCal.add(Calendar.DAY_OF_MONTH, -1);
        long startTime = startCal.getTimeInMillis();

        Calendar endCal;
        endCal = ceilDay(Calendar.getInstance());
        endCal.add(Calendar.DAY_OF_MONTH, -1);
        long endTime = endCal.getTimeInMillis();
        return time > startTime && time < endTime;
    }

    private static boolean isSameYear(long time) {
        Calendar startCal;
        startCal = floorDay(Calendar.getInstance());
        startCal.set(Calendar.MONTH, Calendar.JANUARY);
        startCal.set(Calendar.DAY_OF_MONTH, 1);
        return time >= startCal.getTimeInMillis();
    }

    private static Calendar floorDay(Calendar startCal) {
        startCal.set(Calendar.HOUR_OF_DAY, 0);
        startCal.set(Calendar.MINUTE, 0);
        startCal.set(Calendar.SECOND, 0);
        startCal.set(Calendar.MILLISECOND, 0);
        return startCal;
    }

    private static Calendar ceilDay(Calendar endCal) {
        endCal.set(Calendar.HOUR_OF_DAY, 23);
        endCal.set(Calendar.MINUTE, 59);
        endCal.set(Calendar.SECOND, 59);
        endCal.set(Calendar.MILLISECOND, 999);
        return endCal;
    }

}
